package com.walker.handler;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.walker.anno.ResponseResult;

public class ResponseResultInterceptor extends HandlerInterceptorAdapter{
	
	private static final String RESOPNSE_RESULT_ANNO = "responseResultAnno";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			Class<?> clazz = handlerMethod.getBeanType();
			Method method = handlerMethod.getMethod();
			if(method.isAnnotationPresent(ResponseResult.class)) {//优先判断方法上是否使用了注解
				ResponseResult anno = method.getAnnotation(ResponseResult.class);
				if(!StringUtils.equals(anno.msg(), "doNotOperateReturnResult")) {//方法上注解上若注释了doNotOperateReturnResult表示不封装返回结果
					request.setAttribute(RESOPNSE_RESULT_ANNO,method.getAnnotation(ResponseResult.class));
				}
			}else if(clazz.isAnnotationPresent(ResponseResult.class)) {
				request.setAttribute(RESOPNSE_RESULT_ANNO,clazz.getAnnotation(ResponseResult.class));
			}
		}
		return true;
	}
}